package cn.fastloader.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;


/**
 * (SysUpload)服务
 *
 * @author todoitbo
 * @since 2023-05-21 14:05:46
 */
@Service
public class SysUploadService {



    @Value("${minio.bucket}")
    private String bucketName;
    @Autowired
    RedisTemplate redisTemplate;

    /**
     * description: 创建临时桶
     *
     * @param identify 桶名
     * @return boolean
     * @author bo
     * @date 2023/5/21 15:34
     */

    public boolean createTempBucket(String identify) {
        // 1.校验文件md5是否存在
        Boolean md5Hava = redisTemplate.hasKey(identify);
        if (md5Hava) {
            return true;
        }
        // 2.创建临时桶
        boolean b = MinioUtil.bucketExists(identify);
        if (b) {
            // 存在先删除在创建
            MinioUtil.removeBucket(identify);
        }
        MinioUtil.createBucket(identify);
        // 将MD5存到redis中过期时间为1天，断点续传用到

        redisTemplate.opsForValue().increment(identify,0);
        return false;
    }

    /**
     * description: 合并桶
     *
     * @param identify 文件唯一id
     * @param fileName 文件名
     * @return boolean
     * @author bo
     * @date 2023/5/21 15:37
     */

    public boolean mergeTempBucket(String identify, String fileName) {
        // 1.合并块
        boolean merge = MinioUtil.merge(identify, bucketName, fileName);
        // 删除redis中存在的临时桶的id
        redisTemplate.delete(identify);
        // 3.删除临时桶
        boolean removeBucket = MinioUtil.removeBucket(identify);
        return removeBucket && merge;
    }
}

